package com.mfoyou.agent.web.service.thirdPart;

import java.io.IOException;

import org.mfoyou.agent.common.dao.domain.HuawuYouzan;
import org.mfoyou.agent.common.inf.IIdentity;
import org.mfoyou.agent.utils.common.ArrayListObject;
import org.mfoyou.agent.utils.common.HttpsUtils;
import org.mfoyou.agent.utils.common.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mfoyou.agent.web.service.order.ServiceOrderService;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.client.core.YZClient;
import com.youzan.open.sdk.gen.v3_0_0.api.YouzanShopGet;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanShopGetParams;
import com.youzan.open.sdk.gen.v4_0_0.api.YouzanTradeGet;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetParams;


@Service
public class YouzanService {

    public static String clientId = "2b17a50d0b19c93f8a";

    public static String secret = "793b8e80824ba534f42a0517f52012a3";

    String callbackUrl = "http://api.udpt.cn/youzan/callback";

    String urlPre = "https://open.youzan.com/oauth/";

    @Autowired
    ServiceOrderService serviceOrderService;
    @Autowired
    IIdentity iIdentity;
    String youzanPre = "youzan:token:";

    String youzanPreRefresh = "youzan:refresh:token:";

    Logger logger = Logger.getLogger(YouzanService.class);

    @Autowired
    RedisCacheManger redisCacheManger;

    /**
     * 获取重定向
     *
     * @param userId
     * @return
     */
    public String getUrl(Integer userId) {
        StringBuilder stringBuilder = new StringBuilder(urlPre);
        stringBuilder.append("authorize?client_id=").append(clientId)
                .append("&response_type=code&state=" + userId + "&redirect_uri=").append(callbackUrl);
        return stringBuilder.toString();
    }

    /**
     * 储存token'
     *
     * @param userId
     * @return
     */
    public void getAccessToken(String code, Integer userId) {
        StringBuilder stringBuilder = new StringBuilder(urlPre);
        stringBuilder.append("token?client_id=").append(clientId)
                .append("&client_secret=").append(secret)
                .append("&grant_type=authorization_code&code=" + code + "&redirect_uri=").append(callbackUrl);
        String response = HttpsUtils.get(stringBuilder.toString());
        logger.info(response);
        if (response == null || !response.contains("access_token")) return;
        JSONObject parseObject = JSON.parseObject(response);
        redisCacheManger.setValue(youzanPre + userId, parseObject.getString("access_token"),
                parseObject.getInteger("expires_in"));
        redisCacheManger.setValue(youzanPreRefresh + userId, parseObject.getString("refresh_token"), -1);
        getShop(parseObject.getString("access_token"), userId);
    }

    /**
     * 储存store'
     *
     * @param userId
     * @return
     */
    public void getShop(String token, Integer userId) {
        try (YZClient client = new DefaultYZClient(new Token(token))) {
            YouzanShopGetParams youzanShopGetParams = new YouzanShopGetParams();
            YouzanShopGet youzanShopGet = new YouzanShopGet();
            youzanShopGet.setAPIParams(youzanShopGetParams);
            String result = client.invoke(youzanShopGet);
            logger.info(result);
            JSONObject parseObject = JSONObject.parseObject(result);
            JSONObject response = parseObject.getJSONObject("response");
            String id = response.getString("id");
            String name = response.getString("name");
            String logo = response.getString("logo");
            HuawuYouzan huawuYouzan = new HuawuYouzan();
            huawuYouzan.setUserId(userId);
            huawuYouzan.setYouzanStoreId(id);
            huawuYouzan.setYouzanStoreName(name);
            huawuYouzan.setYouzanStorePic(logo);
            iIdentity.addYouzanData(huawuYouzan);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new YouzanService().getShop("2d7b3cae795f3e4f9a74b906faf6dc9a", 1);
    }

    /**
     * 刷新token
     *
     * @param userId
     * @return
     */
    public String refreshAndGet(Integer userId) {
        String refreshToken = redisCacheManger.getValue(youzanPreRefresh + userId);
        if (refreshToken == null) {
            logger.info("refresh token is null");
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder(urlPre);
        stringBuilder.append("token?client_id=").append(clientId)
                .append("&client_secret=").append(secret)
                .append("&grant_type=refresh_token&refresh_token=" + refreshToken);
        String response = HttpsUtils.get(stringBuilder.toString());
        logger.info(response);
        if (response == null || !response.contains("access_token")) return null;
        JSONObject parseObject = JSON.parseObject(response);
        redisCacheManger.setValue(youzanPre + userId, parseObject.getString("access_token"),
                parseObject.getInteger("expires_in"));
        redisCacheManger.setValue(youzanPreRefresh + userId, parseObject.getString("refresh_token"), -1);
        return parseObject.getString("access_token");
    }

    /**
     * 获取token
     *
     * @param userId
     * @return
     */
    public String getToken(Integer userId) {
        String token = redisCacheManger.getValue(youzanPre + userId);
        if (token != null) {
            logger.info("token token is not null");
            return token;
        }
        return refreshAndGet(userId);
    }

    public int dealWithOrder(String json) {
        logger.info(json);
        JSONObject pushData = JSON.parseObject(json);
        String type = pushData.getString("type");
        if (type != null && type.equals("trade_TradeSellerShip")) {
            HuawuYouzan huawuYouzan = iIdentity.getUserIdByYouzanStoreId(pushData.getString("kdt_id"));
            if (huawuYouzan == null || huawuYouzan.getState() == null || huawuYouzan.getState() != 1) {
                logger.info("youzan info is reject");
                return -2;
            }
            try (YZClient client = new DefaultYZClient(new Token(getToken(huawuYouzan.getUserId())))) {
                YouzanTradeGetParams youzanTradeGetParams = new YouzanTradeGetParams();
                youzanTradeGetParams.setTid(pushData.getString("id"));
                YouzanTradeGet youzanTradeGet = new YouzanTradeGet();
                youzanTradeGet.setAPIParams(youzanTradeGetParams);
                String result = client.invoke(youzanTradeGet);
                if (!result.contains(pushData.getString("id"))) {
                    return -1;
                }
                JSONObject orderData = JSON.parseObject(result);
                return serviceOrderService.addYouzanOrder(orderData, pushData.getString("id"), huawuYouzan);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    public int addYouzanStore(HuawuYouzan huawuYouzan) {
        return iIdentity.addYouzanStore(huawuYouzan);
    }

    public ArrayListObject<?> getStoreInfos(Integer pageId, Integer pageSize, Integer userId, Integer agentId) {
        return iIdentity.getYouzanStores(pageId, pageSize, userId, agentId);
    }

    public int updateYouzan(HuawuYouzan huawuYouzan) {
        return iIdentity.updateYouzan(huawuYouzan);
    }

    public int deleteYouzanStoreInfo(HuawuYouzan huawuYouzan) {
        return iIdentity.deleteYouzan(huawuYouzan);
    }

}
